//引入自己封装的axios
import axios from 'axiosInstance'

const state = {
  user: null, // 当前登录的用户信息
  token: null, // 用户的认证令牌
};

const getters = {
  isLoggedIn(state) {
    return state.user !== null;
  },
  getUser(state) {
    //如果state.user为空 进行checkAuth验证
    return state.user;
  },
  getToken(state) {
    //获取token 如果为空 则哪本地存储中获取
    if(state.token === null){
        state.token = localStorage.getItem('token');  
    }
    return state.token;
  },
};

const mutations = {
  setUser(state, user) {
    state.user = user;
  },
  setToken(state, token) {
    state.token = token;
  },
  clearAuth(state) {
    state.user = null;
    state.token = null;
  },
};

const actions = {
  login({ commit },  formData ) {
    // 调用登录接口，登录用户
    return axios.post("/api/login",formData)
      .then((response) => {
        // 如果登录成功，保存用户的登录状态
        const { token,user } = response.data;
        //如果选择了密码，将密码保存到localStorage
        if(formData.rememberMe){
            localStorage.setItem("token", token);
            localStorage.setItem("username", user.username);
            localStorage.setItem("password", user.password);
        }
        commit('setUser', user);
        commit('setToken', token);
        return response.data;
      })
      .catch((err) => {
        // 如果 token 无效，抛出错误
        throw new Error('error'+err);
      });
  },
  logout({ commit }) {
    // 调用注销接口，注销用户
    return api.logout()
      .then(() => {
        // 如果注销成功，清除用户的登录状态
        commit('clearAuth');
        localStorage.removeItem('user');
        localStorage.removeItem('token');
      })
      .catch(() => {
        // 如果注销失败，抛出错误
        throw new Error('Logout failed');
      });
  },
  checkAuth({ commit }) {//检查本地信息是否有效
    const user = localStorage.getItem('username');
    const token = localStorage.getItem('token');
    if (user && token) {
      // 调用验证接口，验证 token 的有效性
      return axios.get(`/verifyToken`)
        .then(() => {
          // 如果 token 有效，恢复用户的登录状态并返回true
          commit('setUser', user);
          commit('setToken', token);
          console.log("成功");
          return true;
        })
        .catch((err) => {
          // 如果 token 无效，清除用户的登录状态并返回false
          commit('clearAuth');
          localStorage.removeItem('user');
          localStorage.removeItem('token');
          console.log("失败"+err);
          return false;
        });
    } else {
      // 如果没有 token，返回false
      return false;
    }
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
